package com.ilop.sthome.ui.activity.scene;

import android.content.Intent;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.scene.AutomationContract;
import com.ilop.sthome.mvp.present.scene.AutomationPresenter;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.ui.adapter.scene.TriggerInAdapter;
import com.ilop.sthome.ui.adapter.scene.TriggerOutAdapter;
import com.ilop.sthome.ui.dialog.TipDialog;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityAutomationDetailBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * @author skygge
 * @date 2020-01-25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：自动化详情页面
 */
public class AutomationDetailActivity extends ContainLoginActivity<AutomationPresenter, ActivityAutomationDetailBinding> implements AutomationContract.IView {

    private AutomationBean mAutomation;
    private AutomationBean mNewAutomation;
    private String mDeviceName;
    private boolean mModify;
    private boolean isAdd;
    private boolean hasModify = false;

    private TriggerInAdapter mInAdapter;
    private TriggerOutAdapter mOutAdapter;

    private List<DeviceInfoBean> inputList;
    private List<DeviceInfoBean> outputList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_automation_detail;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        isAdd = getIntent().getBooleanExtra(CommonId.KEY_ADD_SCENE, false);
        mModify = getIntent().getBooleanExtra(CommonId.KEY_MODIFY, false);
        mAutomation = (AutomationBean) getIntent().getSerializableExtra(CommonId.KEY_SCENE_DETAIL);
        mNewAutomation = (AutomationBean) getIntent().getSerializableExtra(CommonId.KEY_AUTOMATION);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new AutomationPresenter(mContext, mDeviceName);
    }

    @Override
    protected void initView() {
        super.initView();
        if (!mModify){
            mDBind.btDeleteAutomation.setVisibility(View.GONE);
        }else {
            String title = getString(R.string.automation) + mAutomation.getMid();
            mDBind.tvAutomationName.setText(title);
        }
        mPresent.isDefault(mAutomation);
        inputList = new ArrayList<>();
        outputList = new ArrayList<>();
        if (isAdd) mDBind.btDeleteAutomation.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        super.initData();
        if (isAdd){
            mPresent.isNewForShow(mNewAutomation);
        }else {
            mPresent.isModifyForShow(mModify, mAutomation);
            showSaveUnableToClick();
        }
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.INPUT_CONDITION, DeviceInfoBean.class).observe(this, device -> {
            if (device != null) {
                if (mPresent.checkInput(device)) {
                    inputList.add(device);
                    mPresent.setInputList(inputList);
                    hasModify = true;
                }
                showWhetherToSave();
            }
        });
        LiveDataBus.get().with(CommonId.OUTPUT_CONDITION, DeviceInfoBean.class).observe(this, device -> {
            if (device != null) {
                if (outputList.size() == 0) {
                    outputList.add(device);
                    mPresent.setOutputList(outputList);
                    hasModify = true;
                } else {
                    if (mPresent.checkOutput(device)) {
                        if ("PHONE".equals(device.getDevice_type())) {
                            outputList.add(0, device);
                        } else {
                            outputList.add(device);
                        }
                        mPresent.setOutputList(outputList);
                        hasModify = true;
                    }
                }
                showWhetherToSave();
            }
        });
        LiveDataBus.get().with(CommonId.INPUT_UPDATE, DeviceInfoBean.class).observe(this, device -> {
            mPresent.checkUpdateInput(device);
            hasModify = true;
            showWhetherToSave();
        });
        LiveDataBus.get().with(CommonId.OUTPUT_UPDATE, DeviceInfoBean.class).observe(this, device -> {
            mPresent.checkUpdateOutput(device);
            hasModify = true;
            showWhetherToSave();
        });
        LiveDataBus.get().with(CommonId.DELETE_CONDITION, Boolean.class).observe(this, isInput -> {
            assert isInput !=null;
            mPresent.deleteCondition(isInput);
            hasModify = true;
            showWhetherToSave();
        });
        LiveDataBus.get().with(CommonId.INPUT_CLICK, Integer.class).observe(this, integer ->
                mPresent.updateAction(true, integer));

        LiveDataBus.get().with(CommonId.OUTPUT_CLICK, Integer.class).observe(this, integer ->
                mPresent.updateAction(false, integer));

        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                if (event.getData_str1().length() == 9) {
                    String code = event.getData_str2();
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.INCREASE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            mPresent.sendSuccess(code.substring(4));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    } else if (cmd == SiterCommand.DELETE_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showToast(getString(R.string.delete_success));
                            mPresent.deleteSuccess();
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }else if (cmd == SiterCommand.MODIFY_AUTOMATION) {
                        if (CommonId.KEY_SUCCESS.equals(code.substring(0, 2))) {
                            showToast(getString(R.string.modify_successfully));
                            mPresent.sendSuccess(code.substring(4));
                        } else {
                            showToast(getString(R.string.failed));
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivBack.setOnClickListener(v -> mPresent.whetherToSave(hasModify));
        mDBind.triggerAdd.setOnClickListener(v ->{
            if (mPresent.isTimerOrClick()){
                showToast(getString(R.string.cant_add_conditions));
            }else {
                mPresent.addNewInput();
            }
        });
        mDBind.executiveAdd.setOnClickListener(v -> mPresent.addNewOutput());
        mDBind.tvSaveAutomation.setOnClickListener(v -> {
            mPresent.onSaveAutomation();
            showProgressDialog();
        });

        mDBind.btDeleteAutomation.setOnClickListener(v -> {
            TipDialog dialog = new TipDialog(mContext, ()->{
                showProgressDialog();
                mPresent.onDeleteAutomation(mAutomation.getMid());
            });
            dialog.setMsg(getString(R.string.delete_automation));
            dialog.show();
        });
    }

    @Override
    public void showIsDefault(boolean editable) {
        mDBind.triggerAdd.setVisibility(editable ? View.VISIBLE : View.GONE);
        mDBind.executiveAdd.setVisibility(editable ? View.VISIBLE : View.GONE);
        mDBind.btDeleteAutomation.setVisibility(editable ? View.VISIBLE : View.INVISIBLE);
        mDBind.tvSaveAutomation.setVisibility(editable ? View.VISIBLE : View.GONE);
        mInAdapter = new TriggerInAdapter(mContext);
        mInAdapter.setEditable(editable);
        mDBind.triggerList.setAdapter(mInAdapter);
        mDBind.triggerList.setLayoutManager(new LinearLayoutManager(mContext));
        mOutAdapter = new TriggerOutAdapter(mContext);
        mOutAdapter.setEditable(editable);
        mDBind.executiveList.setAdapter(mOutAdapter);
        mDBind.executiveList.setLayoutManager(new LinearLayoutManager(mContext));
    }

    @Override
    public void showWhetherToSave() {
        if (inputList.size()>0 && outputList.size()>0){
            mDBind.tvSaveAutomation.setTextColor(ContextCompat.getColor(mContext, R.color.main_color));
            mDBind.tvSaveAutomation.setEnabled(true);
        }else {
            mDBind.tvSaveAutomation.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
            mDBind.tvSaveAutomation.setEnabled(false);
        }
    }

    @Override
    public void showSaveUnableToClick() {
        mDBind.tvSaveAutomation.setTextColor(ContextCompat.getColor(mContext, R.color.text_normal));
        mDBind.tvSaveAutomation.setEnabled(false);
    }

    @Override
    public void showInputList(List<DeviceInfoBean> deviceList) {
        inputList = deviceList;
        mInAdapter.setList(deviceList);
    }

    @Override
    public void showOutputList(List<DeviceInfoBean> deviceList) {
        outputList = deviceList;
        mOutAdapter.setList(deviceList);
    }

    @Override
    public void startActivityByIntent(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void showToastMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void finishActivity() {
        dismissProgressDialog();
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mPresent.whetherToSave(hasModify);
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
